package com.itheima.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.itheima.anno.LogOperate;
import com.itheima.excel.StudentListener;
import com.itheima.excel.model.StudentModel;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Result;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.Positive;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/students")
@Validated
public class StudentController {
    @Autowired
    private StudentService studentService;

    /**
     * 分页条件查询学员
     * @param studentQueryParam
     * @return
     */
    @GetMapping
    public Result pageQuery(StudentQueryParam studentQueryParam){
        PageResult<Student> pageResult=studentService.pageQuery(studentQueryParam);
        return Result.success(pageResult);
    }
    /**
     * 删除学员
     */
    @DeleteMapping("/{ids}")
    @LogOperate
    public Result delete(@PathVariable List<Integer> ids){
        log.info("批量删除学员: ids={} ", ids);
        studentService.deleteById(ids);
        return Result.success();
    }
    /**
     * 新增学员
     */
    @PostMapping
    @LogOperate
    public Result save(@RequestBody Student student){
        log.info("新增学员, student: {}", student);
        studentService.save(student);
        return Result.success();
    }
    /**
     * 修改学员
     */
    @PutMapping
    @LogOperate
    public Result update(@RequestBody Student student){
        log.info("修改学员, student: {}", student);
        studentService.update(student);
        return Result.success();
    }
    /**
     * 学员违纪处理
     */
    @PutMapping("/violation/{id}/{score}")
    public Result violation(@PathVariable Integer id, @Positive(message = "分数不能为空或负数") @PathVariable Integer score){
        studentService.violation(id,score);
        return Result.success();
    }
    /**
     * 批量导入学员信息
     * @param clazzId
     * @param file
     * @return
     */
    @PostMapping("/import/{clazzId}")
    public Result doImport(@PathVariable Integer clazzId, MultipartFile file) throws IOException {
        //解析excel，调用业务批量保存
        // 构建excel文件读取监听器
        StudentListener listener = new StudentListener(new ArrayList<>());
        // 读取excel内容
        EasyExcel.read(file.getInputStream(), StudentModel.class, listener).sheet().doRead();
        // 获取读取的结果
        List<StudentModel> stuList = listener.getStuList();
        // 批量导入
        studentService.importStudent(stuList, clazzId);
        return Result.success();
    }

    /**
     * 导出学员信息
     * @param queryParam
     * @param response 只要是下载文件，一定会用到response，且方法返回类型void
     */
    @GetMapping("/export")
    public void export(StudentQueryParam queryParam, HttpServletResponse response) throws IOException {
        // 调用业务层查询符合条件的学员列表
        List<StudentModel> studentModelList = studentService.list(queryParam);
        // 导出excel
        // 单元格的格式化
        WriteCellStyle writeCellStyle = new WriteCellStyle();
        // 样式水平居中
        writeCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 修改下载文件的名称
        response.reset();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=abc.xlsx");

        EasyExcel.write(response.getOutputStream())
                .head(StudentModel.class)
                .registerWriteHandler(new HorizontalCellStyleStrategy(null, writeCellStyle))
                .sheet("学员信息")
                .doWrite(studentModelList);
    }
}
